import 'dart:async';
import 'dart:io';
import '../utils/preference_utils.dart';
import '../app_logger.dart';

/// 服务器信息
class ServerInfo {
  final String name;
  final String url;
  final String domain;
  final String description;

  const ServerInfo({
    required this.name,
    required this.url,
    required this.domain,
    required this.description,
  });

  Map<String, dynamic> toJson() => {
    'name': name,
    'url': url,
    'domain': domain,
    'description': description,
  };

  factory ServerInfo.fromJson(Map<String, dynamic> json) => ServerInfo(
    name: json['name'],
    url: json['url'],
    domain: json['domain'],
    description: json['description'],
  );
}

/// 服务器速度测试结果
class ServerSpeedResult {
  final ServerInfo server;
  final int latencyMs;
  final bool isReachable;
  final DateTime testTime;

  const ServerSpeedResult({
    required this.server,
    required this.latencyMs,
    required this.isReachable,
    required this.testTime,
  });

  Map<String, dynamic> toJson() => {
    'server': server.toJson(),
    'latencyMs': latencyMs,
    'isReachable': isReachable,
    'testTime': testTime.millisecondsSinceEpoch,
  };

  factory ServerSpeedResult.fromJson(Map<String, dynamic> json) => ServerSpeedResult(
    server: ServerInfo.fromJson(json['server']),
    latencyMs: json['latencyMs'],
    isReachable: json['isReachable'],
    testTime: DateTime.fromMillisecondsSinceEpoch(json['testTime']),
  );
}

/// 智能服务器配置管理器
class SmartServerConfig {
  static const String _prefKeyFastestServer = 'smart_server_fastest';
  static const String _prefKeyLastTestTime = 'smart_server_last_test';
  static const Duration _testInterval = Duration(hours: 1); // 每小时重新测试一次

  /// 可用的服务器列表
  static const List<ServerInfo> availableServers = [
    ServerInfo(
      name: 'www.uptimetime.com',
      url: 'wss://www.uptimetime.com/ws',
      domain: 'www.uptimetime.com',
      description: 'www.uptimetime.com'
    ),
    ServerInfo(
      name: 'uptimetime.com',
      url: 'wss://uptimetime.com/ws',
      domain: 'uptimetime.com',
      description: 'uptimetime.com'
    ),
    ServerInfo(
      name: 'www.bdtennis.com',
      url: 'wss://www.bdtennis.com/ws',
      domain: 'www.bdtennis.com',
      description: 'www.bdtennis.com'
    ),
    ServerInfo(
      name: 'bdtennis.com',
      url: 'wss://bdtennis.com/ws',
      domain: 'bdtennis.com',
      description: 'bdtennis.com'
    ),
  ];

  static SmartServerConfig? _instance;
  static SmartServerConfig get instance => _instance ??= SmartServerConfig._();

  SmartServerConfig._();

  ServerSpeedResult? _currentFastestServer;
  Timer? _backgroundTestTimer;
  bool _isTestingInProgress = false;


  /// 初始化
  Future<void> initialize() async {
    await _loadSavedFastestServer();
    _startBackgroundTesting();
    log.d('🚀 智能服务器配置初始化完成');
  }

  /// 获取当前推荐的服务器（智能选择）
  Future<ServerInfo> getRecommendedServer() async {
    // 如果有保存的最快服务器且测试时间不超过1小时，直接使用
    if (_currentFastestServer != null &&
        DateTime.now().difference(_currentFastestServer!.testTime) < _testInterval) {
      log.d('📡 使用缓存的最快服务器: ${_currentFastestServer!.server.name} (${_currentFastestServer!.latencyMs}ms)');
      return _currentFastestServer!.server;
    }

    // 否则使用默认服务器（第一个），并触发后台测试
    log.d('📡 使用默认服务器，后台测试中...');
    _triggerSpeedTest();
    return availableServers.first;
  }

  /// 获取当前最快服务器的结果
  ServerSpeedResult? getCurrentFastestResult() => _currentFastestServer;

  /// 手动触发服务器速度测试
  Future<List<ServerSpeedResult>> testAllServers() async {
    if (_isTestingInProgress) {
      log.d('⏳ 服务器测试正在进行中，跳过重复测试');
      return [];
    }

    _isTestingInProgress = true;
    log.d('🔍 开始测试所有服务器速度...');

    List<ServerSpeedResult> results = [];

    try {
      // 并发测试所有服务器
      final testFutures = availableServers.map((server) => _testServerSpeed(server));
      final testResults = await Future.wait(testFutures);

      results = testResults.where((result) => result.isReachable).toList();

      if (results.isNotEmpty) {
        // 按延迟排序，找到最快的服务器
        results.sort((a, b) => a.latencyMs.compareTo(b.latencyMs));
        final fastest = results.first;

        // 更新最快服务器
        await _updateFastestServer(fastest);
        log.d('🏆 最快服务器: ${fastest.server.name} (${fastest.latencyMs}ms)');
      } else {
        log.d('⚠️ 所有服务器测试失败，使用默认服务器');
      }

    } catch (e) {
      log.d('❌ 服务器测试过程中出错: $e');
    } finally {
      _isTestingInProgress = false;
    }

    return results;
  }

  /// 测试单个服务器速度
  Future<ServerSpeedResult> _testServerSpeed(ServerInfo server) async {
    final stopwatch = Stopwatch()..start();

    try {
      // 使用Socket连接测试域名的443端口（HTTPS）
      final socket = await Socket.connect(
        server.domain.replaceAll('www.', ''), // 移除www前缀避免DNS问题
        443,
        timeout: const Duration(seconds: 5),
      );

      stopwatch.stop();
      socket.destroy();

      final latency = stopwatch.elapsedMilliseconds;
      log.d('✅ ${server.name}: ${latency}ms');

      return ServerSpeedResult(
        server: server,
        latencyMs: latency,
        isReachable: true,
        testTime: DateTime.now(),
      );

    } catch (e) {
      stopwatch.stop();
      log.d('❌ ${server.name}: 不可达 ($e)');

      return ServerSpeedResult(
        server: server,
        latencyMs: 9999, // 使用一个很大的值表示不可达
        isReachable: false,
        testTime: DateTime.now(),
      );
    }
  }

  /// 触发后台速度测试
  void _triggerSpeedTest() {
    if (!_isTestingInProgress) {
      Future.delayed(const Duration(milliseconds: 500), () {
        testAllServers();
      });
    }
  }

  /// 启动后台定期测试
  void _startBackgroundTesting() {
    _backgroundTestTimer?.cancel();
    _backgroundTestTimer = Timer.periodic(const Duration(minutes: 30), (timer) {
      _triggerSpeedTest();
    });

    // 立即执行一次测试（如果缓存过期）
    if (_currentFastestServer == null ||
        DateTime.now().difference(_currentFastestServer!.testTime) > _testInterval) {
      _triggerSpeedTest();
    }
  }

  /// 更新最快服务器
  Future<void> _updateFastestServer(ServerSpeedResult result) async {
    _currentFastestServer = result;

    // 使用PreferenceUtils保存到本地
    await Prefs.setJson(_prefKeyFastestServer, result.toJson());
    await Prefs.setTimestamp(_prefKeyLastTestTime);

    log.d('💾 已保存最快服务器: ${result.server.name} (${result.latencyMs}ms)');
  }

  /// 加载保存的最快服务器
  Future<void> _loadSavedFastestServer() async {
    try {
      final savedJson = Prefs.getJson(_prefKeyFastestServer);
      if (savedJson != null) {
        _currentFastestServer = ServerSpeedResult.fromJson(savedJson);
        log.d('📱 加载保存的最快服务器: ${_currentFastestServer!.server.name} (${_currentFastestServer!.latencyMs}ms)');
      }
    } catch (e) {
      log.d('⚠️ 加载保存的服务器信息失败: $e');
      _currentFastestServer = null;
    }
  }

  /// 清理资源
  void dispose() {
    _backgroundTestTimer?.cancel();
    _backgroundTestTimer = null;
    log.d('🧹 智能服务器配置资源已清理');
  }

  /// 获取所有可用服务器
  static List<ServerInfo> getAllServers() => availableServers;

  /// 根据URL获取服务器名称
  static String getServerName(String url) {
    for (var server in availableServers) {
      if (server.url == url) {
        return server.name;
      }
    }
    return url;
  }

  /// 获取默认服务器URL（用于兼容现有代码）
  static String getDefaultServerUrl() => availableServers.first.url;
}

/// 为了兼容现有代码，保留ServerConfig类
class ServerConfig {
  static List<Map<String, String>> get availableServers =>
    SmartServerConfig.availableServers.map((server) => {
      'name': server.name,
      'url': server.url,
      'description': server.description,
    }).toList();

  static String getDefaultServerUrl() => SmartServerConfig.getDefaultServerUrl();

  static String getServerName(String url) => SmartServerConfig.getServerName(url);

  static List<Map<String, String>> getAllServers() => availableServers;
}